package com.logos.jdbc.base;

import java.sql.*;
import java.util.Scanner;

public class JDBCPreparedStatement {

    public static final String url = "jdbc:mysql://192.168.227.133:3306/jdbcTest";

    public static final String userName = "root";

    public static final String passWord = "123456";

    public static void main(String[] args) throws Exception {
        //1. 注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
//        DriverManager.registerDriver(new Driver());
        //2. 获取连接对象
        Connection connection = DriverManager.getConnection(url, userName, passWord);
        String sql = "select emp_id, emp_name, emp_salary, emp_age from emp where emp_name  = ?";
        //3. 获取执行SQL语句的对象
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        System.out.println("请输入要查询的员工姓名：");
        Scanner scanner = new Scanner(System.in);
        String name = scanner.nextLine();
        preparedStatement.setString(1, name);
        ResultSet resultSet = preparedStatement.executeQuery();

        //5. 得到结果集
        while (resultSet.next()) {
            int empId = resultSet.getInt("emp_id");
            String empName = resultSet.getString("emp_name");
            String empSalary = resultSet.getString("emp_salary");
            int empAge = resultSet.getInt("emp_age");
            System.out.println(empId + "\t" + empName + "\t" + empSalary + "\t" + empAge);
        }
        //6. 关闭资源(先开后关)
        resultSet.close();
        preparedStatement.close();
        connection.close();
    }
}
